package com.web.cms.doc.service;

import com.blue.jdbc.JdbcDataSource;
import com.blue.jdbc.Page;
import com.web.cms.doc.dao.*;
import com.web.cms.doc.model.Doc;
import com.web.cms.doc.model.DocFile;
import com.web.cms.doc.util.DocConvertor;
import com.web.core.util.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service("cmsDocService")
@Transactional
@JdbcDataSource(Const.DS_CMS)
public class DocService
{
	@Autowired
	private DocDao docDao;
	@Autowired
	private DocContentDao docContentDao;
	@Autowired
	private DocFileDao docFileDao;
	@Autowired
	private ChannelDao channelDao;
	@Autowired
	private WebDao webDao;
	
	public DocService()
	{
	}
	
	public Doc save(Doc doc, String fileIds)
	{
		doc.setUpdateTime(new Date());
		if (doc.getId() == null)
		{
			docDao.save(doc);
			channelDao.inc(doc.getChannelId(), "docs", 1);
			webDao.inc(doc.getWebId(), "docs", 1);
		}
		else
		{
			docDao.update(doc);
			docFileDao.setDocId(doc.getId()); // 删除原来的关系
		}
		docContentDao.save(doc.getId(), doc.getContent());
		this.saveDocFile(doc, fileIds);		
		Doc w = docDao.get(doc.getId());
		return w;
	}
	
	private void saveDocFile(Doc doc, String fileIds)
	{
		Set<Integer> idSet = null;
		if (fileIds != null && !fileIds.isEmpty())
		{
			idSet = Stream.of(fileIds.split(",")).map(Integer::valueOf).collect(Collectors.toSet());
		}
		idSet = (idSet == null ? new HashSet<>() : idSet);
		
		List<String> keyList = DocConvertor.parseFileKey(doc.getContent());
		
		if (doc.getPic() != null && !doc.getPic().isEmpty())
		{
			keyList.add(doc.getPic());
		}
		
		List<Integer> idList = docFileDao.listIdByKey(keyList);
		idSet.addAll(idList);
		docFileDao.setDocId(doc.getId(), idSet);
	}

	public Doc get(Integer id)
	{
		Doc doc = docDao.get(id);
		if (doc != null)
		{
			DocFile file = new DocFile();
			file.setDocId(id);
			doc.setFileList(docFileDao.list(file));
			doc.setContent(docContentDao.getContent(id));
		}
		return doc;
	}
	
	public Doc getOne(Integer id)
	{
		Doc doc = docDao.get(id);
		return doc;
	}
	
	public String getContentUrl(Integer id)
	{
		return docDao.getContentUrl(id);
	}
	
	public Page<Doc> list(Doc doc, Page<Doc> page)
	{
		page = docDao.list(doc, page);
		return page;
	}
	
}
